package com.mb.prod.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.mb.common.pojo.Product;
import com.mb.common.utils.MapperUtil;
import com.mb.prod.mapper.ProdMapper;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IndexService {
    @Autowired(required = false)
    private ProdMapper productMapper;
    @Autowired
    private TransportClient client;

    public void indexCreate(String indexName, String type) throws JsonProcessingException {

        IndicesAdminClient indices = client.admin().indices();
        boolean exists=indices.prepareExists(indexName).get().isExists();
        if(!exists){
            //创建索引
            indices.prepareCreate(indexName).get();
        }
        List<Product> products = productMapper.selectProductByPage(0, 100);
        for (Product product : products) {
            String jsonSource = MapperUtil.MP.writeValueAsString(product);
            client.prepareIndex(indexName,type,product.getProductId())
                    .setSource(jsonSource).get();
        }
    }
}
